package com.rainng.coursesystem.controller;

import com.rainng.coursesystem.model.HomeworkItem;
import com.rainng.coursesystem.model.MutualItem;
import com.rainng.coursesystem.model.SubmitHomeworkItem;
import com.rainng.coursesystem.repository.CourseRepository;
import com.rainng.coursesystem.service.HomeworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/homework")
public class HomeworkController {

    @Value("D:\\3")
    private String uploadDir;

    @Autowired
    private HomeworkService homeworkservice;

    @Autowired
    private TaskScheduler taskScheduler;


    @PostMapping("/publishhomework")//教师发布作业内容
    public ResponseEntity<String> publishHomework(
            @RequestParam("file") MultipartFile file,
            @RequestParam String title,
            @RequestParam String text,
            @RequestParam long courseId,
            @RequestParam
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date deadLine) {
        try {
            String message = homeworkservice.TeacherPublishHomework(file, courseId, title, text, deadLine);
            return ResponseEntity.ok(message);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to publish homework" + e.getMessage());
        }
    }

    @GetMapping("/viewhomeworkitem")//教师学生浏览作业
    public ResponseEntity<List<HomeworkItem>> listHomework(@RequestParam Long courseId) {
        List<HomeworkItem> items = homeworkservice.listHomework(courseId);
        return ResponseEntity.ok(items);
    }


    @GetMapping("/downloadhomeworkitem")//教师学生下载作业附件
    public ResponseEntity<Resource> downloadHomeworkItem(@RequestParam UUID homeworkId) {
        try {
            HomeworkItem item = homeworkservice.getHomeworkById(homeworkId);

            if (item != null) {
                Path path = Paths.get(item.getFileData() + "/" + item.getFileName());
                Resource resource = new UrlResource(path.toUri());
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + item.getFileName() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.status(404).body(null);
            }
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    @PostMapping("/submithomework")//学生提交作业
    public ResponseEntity<String> submitHomework(
            @RequestParam("file") MultipartFile file,
            @RequestParam UUID homeworkId,
            @RequestParam long userId) {
        try {
            HomeworkItem item = homeworkservice.getHomeworkById(homeworkId);
            String path = item.getFileData();
            String message = homeworkservice.studentSubmitHomework(file, homeworkId, userId, path);
            return ResponseEntity.ok(message);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to submit homework" + e.getMessage());
        }
    }

    @GetMapping("/teacherviewhomework")//教师阅览作业
    public ResponseEntity<List<SubmitHomeworkItem>> listSubmittedHomework(@RequestParam UUID homeworkId) {
        List<SubmitHomeworkItem> items = homeworkservice.listSubmittedHomework(homeworkId);
        return ResponseEntity.ok(items);
    }

    //@GetMapping("/studentviewhomework")//学生查看自己作业
    /*public ResponseEntity<SubmitHomeworkItem> listStudentHomework(@RequestParam UUID homeworkId,@RequestParam long userId) {
        SubmitHomeworkItem item = homeworkservice.listSubmittedHomeworkByUserId(homeworkId,userId);
        return ResponseEntity.ok(item);
    }
     */

    @GetMapping("/studentviewscore") // 学生查看自己作业的分数
    public ResponseEntity<Long> getStudentHomeworkScore(@RequestParam UUID homeworkId, @RequestParam long userId) {
        SubmitHomeworkItem item = homeworkservice.listSubmittedHomeworkByUserId(homeworkId, userId);
        if (item != null) {
            long score = item.getScore(); // 获取分数
            return ResponseEntity.ok(score); // 只返回分数
        } else {
            return ResponseEntity.notFound().build(); // 如果未找到作业，则返回404
        }
    }


    @PostMapping("/scoringhomework")//给作业打分
    public ResponseEntity<String> scoringHomework(@RequestParam UUID studentHomeworkId, @RequestParam long score) {
        try {
            SubmitHomeworkItem item = homeworkservice.getStudentHomeworkById(studentHomeworkId);
            item.setScore(score);
            homeworkservice.setSorce(item);
            return ResponseEntity.ok("Successfully scored homework");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to score homework" + e.getMessage());
        }
    }


    @GetMapping("/downloadhomework")//教师学生下载提交作业附件
    public ResponseEntity<Resource> downloadHomeWork(@RequestParam UUID studentHomeworkId) {
        try {
            SubmitHomeworkItem item = homeworkservice.getStudentHomeworkById(studentHomeworkId);

            if (item != null) {
                Path path = Paths.get(item.getFileData());
                Resource resource = new UrlResource(path.toUri());
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + item.getFileName() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.status(404).body(null);
            }
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    @PostMapping("/mutualscore")
    public ResponseEntity<String> mutualScore(
            @RequestParam UUID homeworkId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startDate,
            @RequestParam(required = false, defaultValue = "3") int reviewCount) {
        if (reviewCount < 0) {
            return ResponseEntity.badRequest().body("Invalid reviewCount: must be a non-negative integer.");
        }

        // 定义一个Runnable，它将在startDate时间后执行
        Runnable task = () -> {
            try {
                homeworkservice.publishPeerReview(homeworkId, endDate, reviewCount);
            } catch (Exception e) {
                // 处理异常，例如记录日志
                e.printStackTrace();
            }
        };

        // 计算延迟时间，即当前时间到startDate的毫秒数
        long delay = startDate.getTime() - System.currentTimeMillis();
        if (delay < 0) {
            delay = 0; // 如果startDate已经过去，则立即执行
        }

        // 使用taskScheduler安排任务
        taskScheduler.schedule(task, new Date(System.currentTimeMillis() + delay));

        // 立即返回响应
        return ResponseEntity.ok("mutualscore scheduled successfully to start at " + startDate);
    }

    @PostMapping("/studentscore")//给作业打分
    public ResponseEntity<String> studentScore(@RequestParam UUID studentHomeworkId, @RequestParam long score, @RequestParam long userId) {
        try {
            MutualItem item = homeworkservice.getById(studentHomeworkId, userId);
            item.setMutualScore(score);
            homeworkservice.setMutualSorce(item);
            return ResponseEntity.ok("Successfully scored homework");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to score homework" + e.getMessage());
        }
    }

    @GetMapping("/getmutualscore") // 学生查看自己作业的分数
    public ResponseEntity<List<MutualItem>> getMutualScore(@RequestParam UUID studentHomeworkId) {
        List<MutualItem> items = homeworkservice.listSubmittedHomeworkByHomeworkId(studentHomeworkId);
        return items == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(items);
    }

    @GetMapping("/getmutual") // 学生获得自己待互评的作业
    public ResponseEntity<List<MutualItem>> getMutual(@RequestParam Long userId,@RequestParam UUID homeworkId) {
        List<MutualItem> items = homeworkservice.listSubmittedHomeworkByuserkId(userId,homeworkId);
        return items == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(items);
    }
}
